import { reactive } from "vue";
import { cloneDeep, get } from "lodash-es";
import { BaseReponse } from "@/common/utils/request/types";
import { PageList } from "@/types/model/pageList.model";
import { DataTableProps } from "naive-ui";

export interface TableHookOpt<T> {
  api: (params: any) => Promise<BaseReponse<PageList<T>>>;
  queryForm?: Recordable;
  likeKeys?: string[];
  beforeFetch?: (params: any) => void;
}

export const useTableHook = <T>(opt: TableHookOpt<T>) => {
  const tableResult = reactive<DataTableProps>({
    loading: false,
    data: [],
  } as DataTableProps);

  const paginationResult = reactive<any>({
    pageNo: 1,
    pageSize: 10,
    pageCount: 1,
    total: 10,
    ...opt.queryForm,
  });

  const getDataList = async () => {
    const params = cloneDeep(paginationResult);
    if (opt.likeKeys?.length) {
      opt.likeKeys.forEach((key) => {
        if (params.hasOwnProperty(key)) {
          params[key] = `*${params[key]}*`;
        }
      });
    }
    if (opt.beforeFetch) {
      opt.beforeFetch(params);
    }
    delete params.total;
    try {
      tableResult.loading = true;
      const result = await opt.api(params);
      paginationResult.total = get(result, "result.total");
      tableResult.data = (get(result, "result.records") || []) as any[];
      paginationResult.pageCount = get(result, "result.pages");
    } catch (err) {
    } finally {
      tableResult.loading = false;
    }
  };

  const handleChangeSize = async (pageSize: number) => {
    paginationResult.pageNo = 1;
    paginationResult.pageSize = pageSize;
    await getDataList();
  };

  const handleChangePage = async (page: number) => {
    paginationResult.pageNo = page;
    await getDataList();
  };

  return {
    tableResult,
    paginationResult,
    getDataList,
    handleChangePage,
    handleChangeSize,
  };
};
